<template>
  <div class="order-item-wrap">
    <!-- 头部区域开始 -->
    <div class="head-wrap">
      <div>
        <span>下单时间：{{order.create_time}}</span>
        <span>订单编号：{{order.oid}}</span>
      </div>

      <!-- 未付款，倒计时时间还有 -->
      <span class="down-time" v-if="order.status===0 && orderExpireTime > -1">
        <i class="iconfont icon-daojishi"></i>
        <b>付款截止：{{timeText}}</b>
      </span>
    </div>
    <!-- 头部区域结束 -->

    <!-- 内容区域开始 -->
    <div class="content-wrap">
      <div class="column goods">
        <ul>
          <li v-for="orderItem in order.orderItems" :key="orderItem.id">
            <RouterLink :to="`/goods-detail?id=${orderItem.goods_id}`" class="cover-img">
              <img :src="global.FILE_DOMAIN + orderItem.goods_cover_url" alt="" />
            </RouterLink>
            <div class="info">
              <p class="name ellipsis-2">{{orderItem.goods_name}}</p>
              <p class="attr ellipsis-1">{{orderItem.goods_sku_text}}</p>
            </div>
            <div class="price">¥{{(orderItem.pay_money/100).toFixed(2)}}</div>
            <div class="count">x{{orderItem.goods_num}}</div>
            
            <!-- 待评价状态: 展示评价按钮 -->
            <el-button @click="handleShowEvaluate(orderItem)" v-if="[6].includes(orderItem.status) && order.orderItems.length > 1">去评价</el-button>

            <!-- 已完成状态: 展示追加评价按钮 -->
            <el-button @click="handleShowEvaluate(orderItem)" v-if="[7].includes(order.status) && order.orderItems.length > 1">追加评价</el-button>
          </li>
        </ul>
      </div>

      <!-- 状态区域开始 -->
      <div class="column state">
        <!-- 订单状态：-5-已关闭，-4-已删除，-3-已部分退款，-2-已退款，-1-已取消，
          0-待付款，1-已付款，2-待发货，3-已发货，4-已揽件，5-派件中，6-待评价，7-已完成，8-退款中 -->

        <template v-for="(item, index) in status_items" :key="index">
          <p v-if="item.value == order.status" :style="'color: '+ item.color + ';'">{{item.value_txt}}</p>
        </template>
        <!-- 待收货：查看物流 -->
        <!-- 待评价：评价商品 -->
        <!-- 已完成：查看评价 -->
        <p @click="" v-if="order.status===3"><a href="javascript:;" class="green">查看物流</a></p>
      </div>
      <!-- 状态区域结束 -->

      <!-- 金额区域开始 -->
      <div class="column amount">
        <p class="price-wrap">
          <span class="symbol">¥</span>
          <span class="price">{{(order.pay_money/100).toFixed(2)}}</span>
        </p>
        <!-- <p>（含运费：¥{{order.postFee}}）</p> -->
        <template v-for="(item, index) in payChannel" :key="index">
          <p v-if="item.key == order.pay_channel">{{item.value}}</p>
        </template>
      </div>
      <!-- 金额区域结束 -->

      <div class="column action">
        <!-- 待支付：立即付款，查看详情，取消订单 -->
        <!-- 待发货：查看详情，再次购买 -->
        <!-- 待收货：确认收货，查看详情，再次购买 -->
        <!-- 待评价：查看详情，再次购买，退款 -->
        <!-- 已完成：查看详情，再次购买，退款 -->
        <!-- 已取消：查看详情 -->

        <!-- 立即付款 -->
        <el-button @click="handleOrderPay(order.oid)" v-if="order.status===0" type="primary" size="small">立即付款</el-button>

        <!-- 确认收货 -->
        <el-button @click="handleConfirmOrder(order.oid)" v-if="order.status===3" type="primary" size="small">确认收货</el-button>

        <!-- 去评价 -->
        <el-button @click="handleShowEvaluate(order.orderItems[0])" v-if="[6].includes(order.status) && order.orderItems.length == 1">去评价</el-button>

        <!-- 追加评价 -->
        <el-button @click="handleShowEvaluate(order.orderItems[0])" v-if="[7].includes(order.status) && order.orderItems.length == 1">追加评价</el-button>

        <!-- 查看详情 -->
        <p><a :href="`/user/order/${order.oid}`">查看详情</a></p>

        <!-- 取消订单 -->
        <p @click="showCancelOrder(order.oid)" v-if="order.status===0"><a href="javascript:;">取消订单</a></p>

        <!-- 退款 -->
        <p @click="handleRefundOrder(order.oid)" v-if="[1,2,3,4,5].includes(order.status)"><a href="javascript:;">退款</a></p>
      </div>
    </div>
    <!-- 内容区域结束 -->

    <!-- 取消订单弹层开始 -->
    <el-drawer v-model="cancelDrawerVisible" size="25%">
      <template #header>
        <div class="cancel-reason-header">取消订单原因</div>
      </template>
      <template #default>
        <div class="cancel-reason-wrap">
          <div class="reason-item" v-for="(item, index) in reasonList" :key="index" @click="handleCheckReason(item)">
            <span>{{ item }}</span>
            <i class="iconfont" :class="reason == item ? 'icon-xuanzhong active' : 'icon-weixuanzhong'"></i>
          </div>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelDrawerVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancelOrder">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 取消订单弹层结束 -->

    <!-- 评价弹层开始 -->
    <el-dialog
      v-model="evaluateDialogVisible"
      :close-on-click-modal="false"
      title="评价商品"
      width="700"
    >
      <!-- 评价的商品区域 -->
      <div class="evaluate-goods-wrap">
        <!-- 商品图片区域 -->
        <div class="cover-image">
          <img :src="global.FILE_DOMAIN + evaluateGoods.goods_cover_url" alt="">
        </div>

        <div class="goods-info">
          <div class="goods-sku-txt ellipsis-2">{{evaluateGoods.goods_sku_text}}</div>
          <div class="goods-name ellipsis-1">{{evaluateGoods.goods_name}}</div>
        </div>
      </div>

      <!-- 表单区域 -->
      <div class="form-wrap">
        <el-form :model="formParams" ref="refForm">
          <!-- 评价内容 -->
          <el-input
            v-model="formParams.contents"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="请输入评价内容"
          />

          <!-- 评价图片 -->
          <el-form-item style="padding-top: 10px;">
            <el-upload
                class="avatar-uploader"
                :action="global.FILE_SERVER + '/api/v1/image/minioSingleUploadImage'"
                :file-list="imageList"
                list-type="picture-card"
                :limit="3"
                :on-success="handleEvaluateImageSuccess"
                :before-upload="beforeEvaluateImageUpload"
            >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                <template #tip>
                    <div class="el-upload__tip">只能上传jpg/png文件,且不超过500kb,最多上传3张图片</div>
                </template>
            </el-upload>
          </el-form-item>

          <!-- 评分 -->
          <div class="rate-wrap" v-if="status == 6">
            <!-- 综合评价 -->
            <div class="rate-item">
              <span class="rate-text">综合评价</span>
              <el-rate
                v-model="formParams.composite_score"
                size="large"
                :icons="['BellFilled', 'BellFilled', 'BellFilled']"
                void-icon="Bell"
                :colors="['#27BA9B', '#27BA9B', '#27BA9B']"
              />
            </div>

            <!-- 描述相符 -->
            <div class="rate-item">
              <span class="rate-text">描述相符</span>
              <el-rate
                v-model="formParams.conform_score"
                size="large"
                color="#27BA9B"
              />
            </div>

            <!-- 物流服务 -->
            <div class="rate-item">
              <span class="rate-text">物流服务</span>
              <el-rate
                v-model="formParams.logistic_score"
                size="large"
              />
            </div>

            <!-- 服务态度 -->
            <div class="rate-item">
              <span class="rate-text">服务态度</span>
              <el-rate
                v-model="formParams.serve_score"
                size="large"
              />
            </div>
          </div>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="evaluateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEvaluateSubmit">发布</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 评价弹层结束 -->
  </div>
</template>
  
<script setup>
import { watch, ref, reactive, inject } from 'vue'
import { usePayTime } from '@/hooks'
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'

// 请求接口
import { reqCancelOrderAPI, reqConfirmOrderAPI, reqRefundOrderAPI, reqPaymentOrderAPI } from '@/apis/order'
import { reqAddGoodsCommentAPI, reqAppendGoodsCommentAPI } from '@/apis/goodsEvaluate'
import { payChannel } from '@/apis/constant'

import { useUserStore } from '@/stores/modules/user'



// ------------------- 定义全局变量开始 -------------------
// 获取全局对象
const global = inject('global')

const props = defineProps({
    order: {
        type: Object,
        default: () => {}
    },
    status_items: {
      type: Array,
      default: []
    },
    tabsStatus: {
      type: String,
      default: 0
    }
})


const emit = defineEmits(['deleteOrderList', 'updateOrderStatus', 'updateOrderItemStatus'])

const { start, timeText } = usePayTime()

if (props.order.expire_time > -1) {
  start(props.order.expire_time)
}

// 用户存储
const userStore = useUserStore()

let loadingInstance = null
// ------------------- 定义全局变量结束 -------------------


// ------------------- 评价商品功能开始 -------------------
// 定义评价商品
const evaluateGoods = ref({})

// 表单参数
const formParams = reactive({
    oid: 0,
    order_item_id: 0,
    goods_id: 0,
    goods_name: '',
    goods_sku_id: 0,
    goods_sku_text: '',
    username: userStore.profile.user.username,
    avatar_url: userStore.profile.user.avatar_url,
    contents: '',
    image_url: '',
    composite_score: 0,
    conform_score: 0,
    logistic_score: 0,
    serve_score: 0,
    is_append: 0
})

// 图片
const imageList = ref([])

// 是否显示评价弹层
const evaluateDialogVisible = ref(false)

const status = ref(0)
// 处理显示评价弹层
const handleShowEvaluate = (item) => {
  evaluateGoods.value = item

  formParams.oid = item.oid
  formParams.order_item_id = item.id
  formParams.goods_id = item.goods_id
  formParams.goods_name = item.goods_name
  formParams.goods_sku_id = item.goods_sku_id
  formParams.goods_sku_text = item.goods_sku_text

  status.value = item.status

  // 重置表单数据
  formParams.contents = ''
  formParams.image_url = ''
  formParams.composite_score = 0
  formParams.conform_score = 0
  formParams.logistic_score = 0
  formParams.serve_score = 0
  imageList.value = []

  // 显示评价弹层
  evaluateDialogVisible.value = true
}

// 选择评价图片上传之前
const beforeEvaluateImageUpload = async (file) => {
  // 加载提示框
  loadingInstance = ElLoading.service({
    text: '正在上传中',
    background: 'rgba(0, 0, 0, 0.8)'
  })

  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
      ElNotification.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
      ElNotification.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M || isPNG && isLt2M;
}

// 上传评价图片成功
const handleEvaluateImageSuccess = (res) => {
  // 关闭加载提示
  loadingInstance.close()

  if (res.code != 200) {
    ElNotification.error(res.message)
    return false
  }

  imageList.value.push({
    url: res.data.absolute_image_url,
    image_url: res.data.image_url
  })
}

// 提交评价
const handleEvaluateSubmit = async () => {
  if (formParams.contents == '') {
    ElMessage.error('请输入评价内容')
      return false
  }

  if (status.value == 6) {
    // 提交参数判断
    if (formParams.composite_score == 0) {
      ElMessage.error('请选择综合评分')
      return false
    }
    if (formParams.conform_score == 0) {
      ElMessage.error('请选择描述相符评分')
      return false
    }
    if (formParams.logistic_score == 0) {
      ElMessage.error('请选择物流服务评分')
      return false
    }
    if (formParams.serve_score == 0) {
      ElMessage.error('请选择服务态度评分')
      return false
    }
  }

  // 组装图片数据
  let image_url = ''
  if (imageList.value.length > 0) {
    imageList.value.forEach(value => {
      image_url += value.image_url + ','
    });
  }

  formParams.image_url = image_url.substring(0,image_url.length-1)

  if (status.value == 7) {
    formParams.is_append = 1
    // 请求追加评价接口
    await reqAppendGoodsCommentAPI(formParams)
    ElNotification({type: 'success', message: '追评成功'})
  } else {
    // 请求新增评价接口
    await reqAddGoodsCommentAPI(formParams)
    ElNotification({type: 'success', message: '评价成功'})


    // 查找订单明细，将其状态设置为：已完成
    emit('updateOrderItemStatus', formParams.oid, formParams.order_item_id, 7)

    // 判断该订单是否存在未评价的商品
    let flag = false
    props.order.orderItems.forEach(item => {
      if (item.status == 6) {
        flag = true
      }
    })

    // 当是待评价栏时，需要将该订单从列表中删除
    if (props.tabsStatus == 4) {
      if (!flag) {
        emit('deleteOrderList', formParams.oid)
      }
    } else {
      if (!flag) {
        emit('updateOrderStatus', formParams.oid, 7)
      }
    }
  }

  evaluateDialogVisible.value = false
}
// ------------------- 评价商品功能结束 -------------------



// -------------------- 倒计时功能开始 --------------------
const orderExpireTime = ref(0)
watch(timeText, async (newValue, oldValue) => {
  if (newValue == '00分00秒') {
    orderExpireTime.value = -1
    props.order.status = -1
    const result = await reqCancelOrderAPI({oid: props.order.oid, cancel_reason: '订单过期自动取消'})
    if (result.code == 200) {
      // 取消订单成功
      ElNotification({type: 'success', message: '取消订单成功'})
    }
  }
},{
  // 初始化的时候也会执行
  immediate: true,
  deep: true
})
// -------------------- 倒计时功能结束 --------------------



// ------------------- 确认收货功能开始 -------------------
const handleConfirmOrder = (oid) => {
  ElMessageBox.confirm('确定要确认收货吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await reqConfirmOrderAPI(oid)
    ElNotification({type: 'success', message: '确认成功'})

    // 当状态是待收货，需要将该订单从列表中删除
    if (props.tabsStatus == 3) {
      emit('deleteOrderList', oid)
    } else {    
      emit('updateOrderStatus', oid, 6)
    }
  }).catch(() => {})
}
// ------------------- 确认收货功能结束 -------------------



// ------------------- 取消订单功能开始 -------------------
// 弹出层组件
const cancelDrawerVisible = ref(false)
// 取消原因列表
const reasonList = ref([
  '商品无货',
  '不想要了',
  '商品信息填错了',
  '地址信息填写错误',
  '商品降价',
  '其它',
])
// 订单取消原因
const reason = ref('')

const orderId = ref(0)

// 显示取消订单弹层
const showCancelOrder = (oid) => {
  orderId.value = oid
  reason.value = ''
  cancelDrawerVisible.value = true
}

const handleCheckReason = (cancel_reason) => {
  reason.value = cancel_reason
}

// 确定取消订单
const confirmCancelOrder = async () => {
  // 判断取消原因
  if (reason.value == '') {
      ElMessage.error('请选择取消原因!')
      return false
  }

  // 请求
  await reqCancelOrderAPI({oid: orderId.value, cancel_reason: reason.value})
  cancelDrawerVisible.value = false

  // 当状态是待付款栏时，需要将该订单从列表中删除
  if (props.tabsStatus == 1) {
      emit('deleteOrderList', orderId.value)
  } else {
      emit('updateOrderStatus', orderId.value, -1)
  }

  ElNotification({type: 'success', message: '取消订单成功'})
}
// ------------------- 取消订单功能结束 -------------------



// ------------------- 订单支付功能开始 -------------------
const handleOrderPay = (oid) => {
  // import.meta.env.DEV
  // 后台获取微信支付的请求参数
  // const result:any = await reqMpWxPayAPI(oid)
  // wx.requestPayment(result.data)

  
  ElMessageBox.confirm('当前支付功能仅模拟模式?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await reqPaymentOrderAPI(oid)

    // 当状态是待付款栏时，需要将该订单从列表中删除
    if (props.tabsStatus == 1) {
        emit('deleteOrderList', oid)
    } else {
        emit('updateOrderStatus', oid, 1)
    }

    ElNotification({type: 'success', message: '支付成功'})

    // setTimeout(() => {
    //     router.push({path: '/paymentResult', query: {oid}})
    // }, 1000)
  }).catch(() => {})
}
// ------------------- 订单支付功能结束 -------------------



// ------------------- 退款订单功能开始 -------------------
const handleRefundOrder = (oid) => {
  ElMessageBox.confirm('确定要退款吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await reqRefundOrderAPI(oid)

    // 当状态是待发货/待收货栏时，需要将该订单从列表中删除
    if (props.tabsStatus == 2 || props.tabsStatus == 3) {
        emit('deleteOrderList', oid)
    } else {
        emit('updateOrderStatus', oid, 8)
    }

    ElNotification({type: 'success', message: '退款成功'})
  }).catch(() => {})
}
// ------------------- 退款订单功能结束 -------------------
</script>
  
<style scoped lang="scss">
.order-item-wrap {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  // 头部区域
  .head-wrap {
    height: 50px;
    line-height: 50px;
    background: $main-color;
    padding: 0 20px;
    color: #fff;
    display: flex;
    justify-content: space-between;
    span {
      margin-right: 20px;
      &.down-time {
        margin-right: 0;
        float: right;
        i {
          vertical-align: middle;
          margin-right: 3px;
        }
        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }
    .del {
      color: #fff;
      background-color: red;
      padding: 0 30px;
    }
  }

  // 内容区域
  .content-wrap {
    display: flex;
    align-items: stretch;
    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;
      > p {
        padding-top: 10px;
      }
      &:first-child {
        border-left: none;
      }

      // 商品基本信息
      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;
        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;
            align-items: center;
            &:last-child {
              border-bottom: none;
            }
            // 商品图片
            .cover-img {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
              img {
                width: 100%;
                height: 100%;
              }
            }

            // 商品信息
            .info {
              width: 260px;
              text-align: left;
              padding: 5px 10px 0 10px;
              p {
                margin-bottom: 6px;
                &.name {
                  line-height: 20px;
                }
                &.attr {
                  color: #999;
                  font-size: 14px;
                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            // 价格
            .price {
              width: 100px;
            }

            // 数量
            .count {
              width: 80px;
            }
          }
        }
      }

      // 状态
      &.state {
        width: 120px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .green {
          color: $main-color;
        }
      }
      &.amount {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 200px;
        .price-wrap {
          color: $price-color;
          .symbol {
            font-size: 16px;
            padding-right: 2px;
          }
          .price {
            font-size: 20px;
          }
        }
      }
      &.action {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 140px;
        a {
          display: block;
          &:hover {
            color: $main-color;
          }
        }
      }
    }
  }

  // 取消订单
  ::v-deep(.el-drawer__header) {
    margin-bottom: 0;
    padding-bottom: 12px;
    border-bottom: 1px solid #f5f5f5;
  }
  .cancel-reason-header {
    font-weight: bold;
    text-align: center;
  }
  .cancel-reason-wrap {
    margin-top: 0;
    .reason-item {
      display: flex;
      justify-content: space-between;
      padding: 15px 10px;
      font-size: 18px;
      border-bottom: 1px solid #f5f5f5;
      cursor: pointer;
      .active {
        color: $main-color;
      }
      .iconfont {
        font-size: 20px;
      }
    }
  }

  // 评价商品区域
  .evaluate-goods-wrap {
    display: flex;
    align-items: center;
    border-top: 1px solid #f5f5f5;
    padding-top: 10px;
    .cover-image {
      width: 70px;
      height: 70px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .goods-info {
      flex: 1;
      padding-left: 10px;
      .goods-sku-txt {
        font-size: 15px;
        font-weight: bold;
        line-height: 18px;
      }
      .goods-name {
        font-size: 16px;
        margin-top: 10px;
        padding-bottom: 2px;
      }
    }
  }

  // 评价表单区域
  .form-wrap {
    padding-top: 10px;
    .rate-wrap {
      .rate-item {
        display: flex;
        align-items: center;
        .rate-text {
          font-size: 18px;
          padding-right: 10px;
        }
        ::v-deep(.el-rate .el-rate__icon) {
          font-size: 26px;
        }
      }
    }
  }
}
</style>